﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Bzure.Common.Data;
using Bzure.Security.Principal;
using Bzure.Common.Core;

namespace Bzure.Apps.Security.DataAccess
{
    public class UserRepository : RepositoryBase
    {
        static UserRepository()
        {
            BzureUser entity = new BzureUser(string.Empty, string.Empty);
            Type type = entity.GetType();
            AppendDataMap(type, "UserID", () => entity.UserID);
            AppendDataMap(type, "UserName", () => entity.UserName);
            AppendDataMap(type, "Password", () => entity.Password);
            AppendDataMap(type, "State", () => entity.State);
            AppendDataMap(type, "EMail", () => entity.EMail);
            AppendDataMap(type, "OpenID", () => entity.OpenID);
            AppendDataMap(type, "RoleValue", () => entity.RoleValue);
            AppendDataMap(type, "NickName", () => entity.NickName);
            ResultMapDelegate<BzureUser> queryMap = BzureUser_Map;
            QueryMapContainer[entity.GetType()] = queryMap;



        }
        public UserRepository(Bzure.Common.Transactions.ITransactionSupport contractProvider)
            : base(contractProvider)
        {

        }
        public override string TableName
        {
            get
            {
                return "T_Security_Users";
            }
        }
        /// <summary>
        /// 用户实体数据映射
        /// </summary>
        /// <param name="reader"></param>
        /// <returns></returns>
        public static BzureUser BzureUser_Map(DataReader reader)
        {
            BzureUser BzureUser = new BzureUser(reader.GetString("UserID"), reader.GetString("UserName"))
            {
                EMail = reader.GetStringNullable("EMail"),
                Password = reader.GetStringNullable("Password"),
                OpenID = reader.GetStringNullable("OpenID"),
                State = reader.GetInt("State"),
                RoleValue = reader.GetInt("RoleValue"),
                NickName = reader.GetStringNullable("NickName")
            };
            return BzureUser;
        }
        public bool ValidateUser(string UserName, string Password)
        {
            string sql = string.Format("SELECT * FROM {0} WHERE UserName=@UserName AND Password=@Password", this.TableName);
            return !IsNull(new SqlEntityMap<string>(this.ContractProvider, sql)
                .Add("UserName", UserName)
                .Add("Password", Password)
                .AsScalar());
        }
        /// <summary>
        /// 用户是否存在
        /// </summary>
        /// <param name="UserName"></param>
        /// <returns></returns>
        public bool ExistsUserName(string UserName)
        {
            string sql = string.Format("SELECT * FROM {0} WHERE UserName=@UserName", this.TableName);
            return !IsNull(new SqlEntityMap<string>(this.ContractProvider, sql)
                .Add("UserName", UserName)
                .AsScalar());
        }
        /// <summary>
        /// 用户是否存在
        /// </summary>
        /// <param name="UserName"></param>
        /// <returns></returns>
        public bool ExistsUserID(string UserID)
        {
            string sql = string.Format("SELECT * FROM {0} WHERE UserID=@UserID", this.TableName);
            return !IsNull(new SqlEntityMap<string>(this.ContractProvider, sql)
                .Add("UserID", UserID)
                .AsScalar());
        }
        /// <summary>
        /// 创建新用户
        /// </summary>
        /// <param name="User"></param>
        /// <returns>是否成功</returns>
        public bool CreateUser(BzureUser User)
        {
            string sql = string.Format("INSERT INTO  {0}(UserID,UserName,Password,State,EMail,OpenID,RoleValue,NickName) VALUES (@UserID, @UserName, @Password, @State, @EMail, @OpenID,@RoleValue,@NickName)", this.TableName);

            int ret = new SqlEntityMap<string>(this.ContractProvider, sql)
                .AddString("UserID", User.UserID)
                .AddString("UserName", User.UserName)
                .AddString("Password", User.Password)
                .AddInt("State", User.State)
                .AddString("EMail", User.EMail)
                .AddString("OpenID", User.OpenID)
                .AddInt("RoleValue", User.RoleValue)
                .AddString("NickName", User.NickName)
                .AsNonQuery();
            if (ret > 0)
                this.MarkPersistenceState(User, true);
            return ret > 0;
        }
        /// <summary>
        /// 改变用户密码
        /// </summary>
        /// <param name="UserName">用户名</param>
        /// <param name="Password">密码密文</param>
        /// <returns>是否成功</returns>
        public bool ChangePassword(string UserName, string Password)
        {
            string sql = string.Format("UPDATE {0} SET Password=@Password WHERE UserName=@UserName", this.TableName);
            return new SqlEntityMap<string>(this.ContractProvider, sql)
               .AddString("Password", Password)
               .AddString("UserName", UserName)
               .AsNonQuery() > 0;
        }
        /// <summary>
        /// 设置用户状态
        /// </summary>
        /// <param name="UserName"></param>
        /// <param name="State"></param>
        /// <returns></returns>
        public bool SetUserState(string UserName, int State)
        {
            string sql = string.Format("UPDATE {0} SET State=@State WHERE UserName=@UserName", this.TableName);
            return new SqlEntityMap<string>(this.ContractProvider, sql)
               .AddInt("State", State)
               .AddString("UserName", UserName)
               .AsNonQuery() > 0;
        }
        /// <summary>
        /// 获取用户实体
        /// </summary>
        /// <param name="UserName"></param>
        /// <returns></returns>
        public BzureUser GetUserByName(string UserName)
        {
            string sql = string.Format("SELECT * FROM  {0} WHERE UserName=@UserName", this.TableName);
            return new SqlEntityMap<BzureUser>(this.ContractProvider, sql)
                .AddString("UserName", UserName)
                .SetMap(BzureUser_Map)
                .AsSingle();
        }
        /// <summary>
        /// 获取用户
        /// </summary>
        /// <param name="EMail"></param>
        /// <returns></returns>
        public BzureUser GetUserByEMail(string EMail)
        {
            if (EMail.IsNullOrEmpty())
                return default(BzureUser);
            string sql = string.Format("SELECT * FROM  {0} WHERE EMail=@EMail", this.TableName);
            return new SqlEntityMap<BzureUser>(this.ContractProvider, sql)
                .AddString("EMail", EMail)
                .SetMap(BzureUser_Map)
                .AsSingle();
        }
        /// <summary>
        /// 获取用户实体
        /// </summary>
        /// <param name="OpenID">OpenID</param>
        /// <returns></returns>
        public BzureUser GetUserByOpenID(string OpenID)
        {
            string sql = string.Format("SELECT * FROM  {0} WHERE OpenID=@OpenID", this.TableName);
            return new SqlEntityMap<BzureUser>(this.ContractProvider, sql)
                .AddString("OpenID", OpenID)
                .SetMap(BzureUser_Map)
                .AsSingle();
        }
        /// <summary>
        /// 获取所有用户
        /// </summary>
        /// <returns></returns>
        public BzureUser[] GetAllUsers()
        {
            string sql = string.Format("SELECT * FROM  {0} ", this.TableName);
            return new SqlEntityMap<BzureUser>(this.ContractProvider, sql)
                .SetMap(BzureUser_Map)
                .AsList().ToArray();
        }
        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="userid"></param>
        public bool DeleteUser(string userid)
        {
            string sql = string.Format("DELETE FROM {0}  WHERE UserID=@UserID", this.TableName);
            return new SqlEntityMap<string>(this.ContractProvider, sql)
               .AddString("UserID", userid)
               .AsNonQuery() > 0;
        }
        /// <summary>
        /// 获取用户
        /// </summary>
        /// <param name="userid"></param>
        /// <returns></returns>
        public BzureUser GetUserByID(string userid)
        {
            string sql = string.Format("SELECT * FROM  {0} WHERE UserID=@UserID", this.TableName);
            return new SqlEntityMap<BzureUser>(this.ContractProvider, sql)
                .AddString("UserID", userid)
                .SetMap(BzureUser_Map)
                .AsSingle();
        }
        /// <summary>
        /// 昵称是否存在
        /// </summary>
        /// <param name="NickName"> 昵称</param>
        /// <returns></returns>
        public bool ExistsNickName(string NickName)
        {
            string sql = string.Format("SELECT * FROM {0} WHERE NickName=@NickName", this.TableName);
            return !IsNull(new SqlEntityMap<string>(this.ContractProvider, sql)
                .Add("NickName", NickName)
                .AsScalar());
        }
        /// <summary>
        /// 设置昵称
        /// </summary>
        /// <param name="UserName">用户名</param>
        /// <param name="NickName">昵称</param>
        /// <returns></returns>
        public bool SetNickName(String UserName, string NickName)
        {
            string sql = string.Format("UPDATE {0} SET NickName=@NickName WHERE UserName=@UserName", this.TableName);
            return new SqlEntityMap<string>(this.ContractProvider, sql)
               .AddString("NickName", NickName)
               .AddString("UserName", UserName)
               .AsNonQuery() > 0;
        }
        public BzureUser[] GetUsers(string[] Ids)
        {
            if (Ids.IsNullOrEmpty())
                return default(BzureUser[]);
            string s = string.Join("','", Ids);
            s = string.Format("'{0}'", s);

            string sql = string.Format("SELECT * FROM  {1} WHERE UserID IN({0})", s, this.TableName);
            return new SqlEntityMap<BzureUser>(this.ContractProvider, sql)
                .SetMap(BzureUser_Map)
                .AsList().ToArray();
        }
        /// <summary>
        /// 获取总用户数
        /// </summary>
        /// <returns></returns>
        public long GetAllUserCount()
        {
            string sql = string.Format("SELECT COUNT(*) FROM  {0} ", this.TableName);
            return long.Parse(new SqlEntityMap<string>(this.ContractProvider, sql)
               .AsScalar().ToString());
        }
        /// <summary>
        /// 验证用户
        /// </summary>
        /// <param name="EMail"></param>
        /// <param name="EncryptPassword"></param>
        /// <returns></returns>
        public bool ValidateEMailUser(string EMail, string EncryptPassword)
        {
            string sql = string.Format("SELECT * FROM {0} WHERE EMail=@EMail AND Password=@Password", this.TableName);
            return !IsNull(new SqlEntityMap<string>(this.ContractProvider, sql)
                .Add("EMail", EMail)
                .Add("Password", EncryptPassword)
                .AsScalar());
        }
        /// <summary>
        /// 邮箱是否存在
        /// </summary>
        /// <param name="NickName"> 邮箱</param>
        /// <returns></returns>
        public bool ExistsEMail(string EMail)
        {
            string sql = string.Format("SELECT * FROM {0} WHERE EMail=@EMail", this.TableName);
            return !IsNull(new SqlEntityMap<string>(this.ContractProvider, sql)
                .Add("EMail", EMail)
                .AsScalar());
        }
    }
}
